package work.soho.proxy.aliyun.parts;

import com.aliyuncs.ecs.model.v20140526.DescribeKeyPairsRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeKeyPairsResponse;
import com.aliyuncs.ecs.model.v20140526.ImportKeyPairRequest;
import com.aliyuncs.ecs.model.v20140526.ImportKeyPairResponse;
import lombok.extern.log4j.Log4j2;
import work.soho.proxy.utils.RsaUtils;

import java.io.*;

/**
 * 导入登录服务器的秘钥
 */
public class ImportKeyPairPart extends BasePart implements IPart{
    @Override
    public boolean isExist() {
        DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
        describeKeyPairsRequest.setKeyPairName(configure.getKeyPairName());
        DescribeKeyPairsResponse describeKeyPairsResponse = callOpenApi(describeKeyPairsRequest);
        return describeKeyPairsResponse.getTotalCount()>0;
    }
    @Override
    public String getId() {
        return configure.getKeyPairName();
    }

    @Override
    public void drop() {
        //无需处理
    }

    @Override
    public void create() throws AliyunPartsException {
        try {
            ImportKeyPairRequest importKeyPairRequest = new ImportKeyPairRequest();
            importKeyPairRequest.setKeyPairName(configure.getKeyPairName());
            importKeyPairRequest.setPublicKeyBody(RsaUtils.getOrCreatePublicKey(configure.getLocalPublicKeyName()));

            ImportKeyPairResponse importKeyPairResponse = callOpenApi(importKeyPairRequest);
        } catch (Exception e) {
            throw new AliyunPartsException("同步密钥对到阿里云失败");
        }
    }

    @Override
    public void start() {
        //无需处理
    }

    @Override
    public void configure() {

    }
}
